//
//  WBNetWorkManager.swift
//  CZweibo
//
//  Created by jyh on 2017/12/10.
//  Copyright © 2017年 jyh. All rights reserved.
//

import UIKit
import Alamofire


class WBNetWorkManager {

    // 单例
    static let shared = WBNetWorkManager()
    
    // 如果回去不到返回数据是因为没有类型"text/plain".要把这个添加上就可以了
    /*
     static let shared: WBNetWorkManager = {
     
     // 实例化对象
     let instance = WBNetWorkManager()
     
     instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
     
     // 返回实例化对象
     return instance
     }()
     */
    
    // 用户账户懒加载属性
    lazy var userAccount = WBUserAccount()

    // 用户登录标记
    var userlogon: Bool {
        return userAccount.access_token != nil
    }
    
    
    // 负责拼接 token 的网络请求方法
    func tokenRequest(method: HTTPMethod = .get, url: URLConvertible, parameters: [String: Any]?, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->() ) {
        
        guard let token = userAccount.access_token else {

            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotifcation), object: "bad token")
            
            completion(nil, false)
            return
        }
        
        var parameters = parameters
        
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        // parameters这里一定会有值所以用强行解包
        parameters!["access_token"] = token
        
        request(url: url, parameters: parameters, completion: completion)
    }
    
    func request(method: HTTPMethod = .get, url: URLConvertible, parameters: [String: Any]?, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->() ) {
        
        Alamofire.request(url, method: method, parameters: parameters).validate { request, response, data in
            
            if response.statusCode == 403 {
                nsLog("连接失败")
                completion(nil, false)
            }
            
            return .success
            }
            .responseJSON { response in
                
                completion(response.value as AnyObject, true)
                
        }
    }
    
    
}
